﻿using STHPMS1.DAL.D_Core;
using STHPMS1.ICore.I_DAL.Repository;
using System.Data;
using System.Data.SqlClient;
using STHPMS1.ICore.I_Entity;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Serv;

namespace STHPMS1.DAL.D_Repository
{
    public class S_ApplyRepository : DalBase, IS_Apply
    {
        public string SaveApplyBack(STHPMS1.ICore.I_Entity.Stmpms1.IS_Apply a)
        {
            using (IDbConnection conn = Adapter.OpenDbConnection())
           {
                conn.Open();
                string sql = string.Format("select APPLYID from S_Apply where APPRDID='{0}' and APPBEGINMP={1} and APPENDMP={2} and DIRECTION_DICTID={3}", a.Apprdid, a.Appbeginmp, a.Appendmp,a.Direction_Dictid);
                IDbCommand cmmd = conn.CreateCommand();
                cmmd.CommandText = sql;
                object obj = cmmd.ExecuteScalar();
               if(obj==null)
               {
                  string id  = MyApp.Locator.GetInstance<IKeyGenrateService>().NewGuid();
                  sql = string.Format("insert into S_Apply values('{0}','{1}',{2},{3},{4})",id,a.Apprdid,a.Appbeginmp,a.Appendmp,a.Direction_Dictid);
                  cmmd.CommandText = sql;
                  cmmd.ExecuteNonQuery();
                  return id;
               }
               else
               {
                   return obj.ToString();
               }
           }
        }

        /// <summary>
        /// 返回路段指定时间的交通量
        /// </summary>
        /// <param name="b"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public DataTable GetApply(ICore.I_Entity.Stmpms1.IB_Invntory b)
        {
            DataTable table = new DataTable();
            using (SqlConnection sqlCon = new SqlConnection(Adapter.ConnectionString))
            {
                string sql = "";
                
                    sql = string.Format(@"select  * from S_TRFVOLSURVEY a inner join S_APPLY b
on a.APPLYID = b.APPLYID where APPRDID='{0}' and datediff(year,obvtm,'{1}')=0 and b.DIRECTION_DICTID={2}
and (APPBEGINMP<= {3} and APPENDMP>={4})",b.Rdwayid,b.Begindate,b.Direction_Dictid,b.Beginmp,b.Endmp);
               
               
                using (SqlDataAdapter da = new SqlDataAdapter(sql, sqlCon))
                {

                    da.Fill(table);
                    da.FillSchema(table, SchemaType.Source);
                }
            }
            return table;

        }

    }
}
